import { parse } from 'cookie-parse'

export const state = () => ({
  token: '',
  orderId: '',
})

export const mutations = {
  SET_TOKEN(state, data) {
    state.token = data
    this.$cookies.set('_token', data, { maxAge: 60 * 60 * 24 * 7 })
  },
  SET_ORDER_ID(state, data) {
    setOrderId(data)
    this.$cookies.set('_order', data, { maxAge: 60 * 60 * 24 * 7 })
  },
}

export const actions = {
  nuxtServerInit({ commit }, { req }) {
    const cookie = req.headers.cookie || ''

    const token = parse(cookie)._token
    const order = parse(cookie)._order
    if (token) {
      commit('SET_TOKEN', token)
    }
    if (order) {
      commit('SET_ORDER_ID', order)
    }
  },
  async createToken({ commit }) {
    const res = await this.$axios.get('productApi/createToken', {
      header: {
        authorization: '321321321321321322222132',
      },
    })

    commit('SET_TOKEN', res.data.token)
  },
}

export const getters = {
  token: (state) => state.token,
  orderId: (state) => state.orderId,
}
